#include "timecodechecker.h"
#include <QVBoxLayout>
#include <sys/stat.h>
#include <stdio.h>
#include <QFile>
#include <QFileDialog>
#include <QTextStream>

TimecodeChecker::TimecodeChecker(QString filepath, int width, int height, QWidget *parent) :
    QDialog(parent),
    BLOCKSIZE(width*height),
    m_ImageWidth(width),
    m_ImageHeight(height),
    STRBLOCKSIZE(256)
{
    m_Filename = new QString(filepath);
    m_fp = fopen64(m_Filename->toLatin1().data(),"r");
    m_CurrentTimeStamp = new QString("");
    m_LastTimeStamp = new QString("");

    struct stat64 buf;
    int ret = stat64(m_Filename->toLatin1().data(), &buf);
    m_FrameCount = buf.st_size / (BLOCKSIZE+STRBLOCKSIZE);

    misFrameList = new QStringList();
    resultBrowser = new QTextBrowser();
    btnStart = new QPushButton(tr("Start"));
    btnSave2File = new QPushButton(tr("Save result to file"));
    btnClose = new QPushButton(tr("Close"));

    QVBoxLayout * layout = new QVBoxLayout();
    this->setLayout(layout);
    layout->addWidget(resultBrowser);
    layout->addWidget(btnStart);
    layout->addWidget(btnSave2File);
    layout->addWidget(btnClose);

    connect(btnStart, SIGNAL(clicked()), SLOT(onStartClicked()));
    connect(btnClose,SIGNAL(clicked()),SLOT(close()));
    connect(btnSave2File,SIGNAL(clicked()),SLOT(onSave2FileClicked()));
}

void TimecodeChecker::onStartClicked()
{
    QString file = QFileDialog::getExistingDirectory(this, tr("Select save File"), tr("/home"));
    QString fileC(file);
    fileC.append("/capturedframs.txt");
    QFile newFile1(fileC);
    if (newFile1.open(QIODevice::ReadWrite |QIODevice::Text)) {
        QTextStream out(&newFile1);
        out << m_FrameCount << " frames" << endl;
        for (int i=0; i<m_FrameCount; i++) {
            readFrame(i);
            out << i << " " << *m_CurrentTimeStamp << endl;
        }

        resultBrowser->append(tr("%1 frames in total, %2 frame(s) is(are) dropped\n").arg(m_FrameCount).arg(misFrameList->count()));
        if (!misFrameList->isEmpty()) {
            resultBrowser->append("Missing frames:\n");
            for (int i=0; i<misFrameList->count(); i++) {
                resultBrowser->append(tr("%1 %2").arg(i+1).arg(misFrameList->at(i)));
            }
            out << misFrameList->count() << " frames are missing" << endl;
            out << "First framedrop: " << misFrameList->first() << endl;
        }
    }
    if (!misFrameList->isEmpty())
    {
        QString fileM(file);
        fileM.append("/missingframes.txt");
        QFile newFile2(fileM);
        if (newFile2.open(QIODevice::ReadWrite |QIODevice::Text)) {
            QTextStream out(&newFile2);
            out << misFrameList->count() << " frames are missing" << endl;
            for (int i=0; i<misFrameList->count(); i++) {
                out << misFrameList->at(i) << endl;
            }
        }
        newFile2.close();
    }

    newFile1.close();
}

void TimecodeChecker::readFrame(off64_t iframe)
{
    //todo
    if(m_fp)
    {
        off64_t ret = fseeko64(m_fp, iframe*(BLOCKSIZE+STRBLOCKSIZE), SEEK_SET);
        fseeko64(m_fp, iframe*(BLOCKSIZE+STRBLOCKSIZE)+BLOCKSIZE, SEEK_SET);
        char strbuf[STRBLOCKSIZE];
        fread(strbuf, STRBLOCKSIZE, 1, m_fp);
        if(m_CurrentTimeStamp)
        {
            m_CurrentTimeStamp->clear();
            m_CurrentTimeStamp->append(QString("%1").arg(strbuf));
            resultBrowser->append(tr("%1 %2").arg(iframe).arg(*m_CurrentTimeStamp));

            if (iframe>0) {
                int lastFrame = m_LastTimeStamp->right(2).toInt();
                int lastSec = m_LastTimeStamp->right(5).left(2).toInt();
                int lastMin = m_LastTimeStamp->left(5).right(2).toInt();
                int lastHour = m_LastTimeStamp->left(2).toInt();

                int curFrame = m_CurrentTimeStamp->right(2).toInt();
                int curSec = m_CurrentTimeStamp->right(5).left(2).toInt();
                int curMin = m_CurrentTimeStamp->left(5).right(2).toInt();
                int curHour = m_CurrentTimeStamp->left(2).toInt();

                int diff = curFrame - lastFrame +
                        30 * (curSec - lastSec) +
                        60 * 30 * (curMin - lastMin) +
                        60 * 60 * 30 * (curHour - lastHour);
                if (diff > 1) {
                    int misFrame = lastFrame;
                    int misSec=lastSec, misMin=lastMin, misHour = lastHour;
                    for (int i=1; i<diff; i++) {
                        misFrame ++;
                        if (misFrame >= 30) {
                            misSec ++;
                            misFrame = 0;
                            if (misSec >= 60) {
                                misMin ++;
                                misSec = 0;
                                if (misMin >= 60) {
                                    misHour ++;
                                    misMin = 0;
                                }
                            }
                        }
                        misFrameList->append(tr("%1:%2:%3;%4").arg(misHour).arg(misMin).arg(misSec).arg(misFrame));
                    }
                }
            }
            m_LastTimeStamp->clear();
            m_LastTimeStamp->append(m_CurrentTimeStamp);
        }
    }
}

void TimecodeChecker::onSave2FileClicked()
{
//    //todo
//    QString file = QFileDialog::getSaveFileName(this, tr("Select save File"), tr("/home"));
//    QFile newFile(file);
//    if (newFile.open(QIODevice::ReadWrite |QIODevice::Text)) {
//        QTextStream out(&newFile);
//        out << resultBrowser->toPlainText();
//    }
}
